<template>
  <div>
    <!-- 筛选条件 -->
    <div style="margin-bottom: 20px; padding: 15px; background-color: #f8f9fa; border-radius: 4px;">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-select v-model="review" placeholder="请选择审核状态" clearable @change="handleReviewChange">
            <el-option label="待审核" :value="0" />
            <el-option label="审核通过" :value="1" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="handleFilter">筛选</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-col>
      </el-row>
    </div>

    <el-table :data="tableData" style="width: 100%" :header-cell-style="{ 'text-align': 'center' }">
      <el-table-column prop="id" label="ID" align="center" />
      <el-table-column prop="category" label="赛事分类" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.category == 1">
            足球
          </span>
          <span v-if="scope.row.category == 2">
            篮球
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="pass_lx_text" label="过关类型" align="center" />
      <el-table-column prop="expert_info.nickname" label="专家" align="center" />

      <el-table-column prop="show_lx_text" label="位置" align="center" />
      <el-table-column prop="title" label="标题" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.title">{{ scope.row.title }}</span>
          <!-- <span v-else-if="scope.row.matchList && scope.row.matchList.length > 0"></span> -->
          <span v-else>暂无标题</span>
        </template>
      </el-table-column>
      <el-table-column label="赛事信息" align="center" width="200">
        <template slot-scope="scope">
          <div v-if="scope.row.matchList && scope.row.matchList.length > 0">
            <div
              v-for="(match, index) in scope.row.matchList"
              :key="index"
              style="margin-bottom: 8px; padding: 5px; background-color: #f5f7fa; border-radius: 4px;"
            >
              <div style="font-weight: bold; margin-bottom: 3px;">
                {{ match.home_team_name }} VS {{ match.away_team_name }}
              </div>
              <div style="font-size: 12px; color: #909399;">
                {{ match.competition_name }}
              </div>
            </div>
          </div>
          <span v-else style="color: #909399;">暂无赛事</span>
        </template>
      </el-table-column>

      <el-table-column prop="review" label="审核状态" align="center">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.review === 0" type="warning">待审核</el-tag>
          <el-tag v-else-if="scope.row.review === 1" type="success">审核通过</el-tag>
          <el-tag v-else type="info">未知</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="create_time" label="生成时间" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.create_time | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button size="small" type="primary" @click="handleButton1Click(scope.row)">审核</el-button>
          <el-button size="small" type="danger" @click="handleButton2Click(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="tabListPage">
      <el-pagination
        :current-page="currentPage"
        :page-sizes="pageSizes"
        :page-size="PageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalCount"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 方案详情对话框 -->
    <el-dialog title="方案详情" :visible.sync="dialogFormVisible" width="80%" :close-on-click-modal="false">
      <div v-if="currentScheme">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-card>
              <div slot="header" class="clearfix">
                <span>基本信息</span>
              </div>
              <el-form label-width="100px">
                <el-form-item label="方案ID:">
                  <span>{{ currentScheme.id }}</span>
                </el-form-item>
                <el-form-item label="方案标题:">
                  <span>{{ currentScheme.title || '无标题' }}</span>
                </el-form-item>
                <el-form-item label="过关类型:">
                  <el-tag :type="currentScheme.pass_lx | passLxFilter">
                    {{ currentScheme.pass_lx_text }}
                  </el-tag>
                </el-form-item>
                <el-form-item label="显示类型:">
                  <el-tag :type="currentScheme.show_lx | showLxFilter">
                    {{ currentScheme.show_lx_text }}
                  </el-tag>
                </el-form-item>
                <el-form-item label="价格:">
                  <span>¥{{ currentScheme.price }}</span>
                </el-form-item>
                <el-form-item label="结果状态:">
                  <el-tag :type="currentScheme.result_status | resultStatusFilter">
                    {{ currentScheme.result_status | resultStatusNameFilter }}
                  </el-tag>
                </el-form-item>
                <el-form-item label="销售状态:">
                  <el-tag :type="currentScheme.sale_status | saleStatusFilter">
                    {{ currentScheme.sale_status | saleStatusNameFilter }}
                  </el-tag>
                </el-form-item>
                <el-form-item label="成功/失败:">
                  <span>{{ currentScheme.success_count }}/{{ currentScheme.fail_count }}</span>
                </el-form-item>
                <el-form-item label="创建时间:">
                  <span>{{ currentScheme.create_time | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
                </el-form-item>
              </el-form>
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card>
              <div slot="header" class="clearfix">
                <span>方案内容</span>
              </div>
              <div v-if="currentScheme.charge_content" style="max-height: 600px; overflow-y: auto;">
                <div v-if="currentScheme.content_type === 1">
                  <p><strong>免费内容:</strong></p>
                  <div v-html="currentScheme.free_content" />
                  <p><strong>付费内容:</strong></p>
                  <div v-html="getChargeContent(currentScheme.charge_content)" />
                </div>
                <div v-else>
                  <div v-html="currentScheme.free_content" />
                </div>
              </div>
              <div v-else>
                <p>暂无内容</p>
              </div>
            </el-card>
          </el-col>
        </el-row>
        <el-row
          v-if="currentScheme.matchList && currentScheme.matchList.length > 0"
          :gutter="20"
          style="margin-top: 20px;"
        >
          <el-col :span="24">
            <el-card>
              <div slot="header" class="clearfix">
                <span>包含赛事 ({{ currentScheme.matchList.length }}场)</span>
              </div>
              <el-table :data="currentScheme.matchList" border>
                <el-table-column prop="competition_name" label="联赛" width="120" />
                <el-table-column prop="home_team_name" label="主队" width="120" />
                <el-table-column prop="away_team_name" label="客队" width="120" />
                <el-table-column prop="match_time" label="比赛时间" width="150">
                  <template slot-scope="{row}">
                    <span>{{ row.match_time | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="lottery_tag" label="彩种" width="100" />
                <el-table-column label="赔率" width="200">
                  <template slot-scope="{row}">
                    <div v-if="row.odds && row.odds.length > 0">
                      <el-tag
                        v-for="(odd, index) in row.odds"
                        :key="index"
                        :type="odd.is_recommend ? 'success' : 'info'"
                        size="mini"
                        style="margin-right: 5px;"
                      >
                        {{ odd.label }}: {{ odd.value }}
                      </el-tag>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </el-card>
          </el-col>
        </el-row>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">
          关闭
        </el-button>
        <el-button type="success" @click="handleAudit(currentScheme)">
          审核
        </el-button>
      </div>
    </el-dialog>

    <div>
      <el-dialog title="修改" :visible.sync="dialogTableModify" :before-close="modifyForm" :close-on-click-modal="false">
        <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="100px" class="demo-ruleForm">
          <el-form-item label="分类标签" prop="name">
            <el-select v-model="ruleForm.category" placeholder="请选择" @change="handleSelectChange">
              <el-option v-for="(item, index) in options" :key="index" :label="item.label" :value="item.valuess" />
            </el-select>
          </el-form-item>
          <div @click="showExpertSelector = true">
            <el-form-item label="选择老师" prop="name">
              <el-select
                v-model="ruleForm.expert_id"
                style="pointer-events: none;"
                placeholder="请选择"
                @change="selectChangeExpert"
              >
                <el-option
                  v-for="(item, index) in expertDataList"
                  :key="index"
                  :label="item.nickname"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </div>
          <el-form-item label="串子分类">
            <el-radio-group v-model="ruleForm.pass_lx">
              <el-radio :label="1">单场</el-radio>
              <el-radio :label="2">2串1</el-radio>
              <el-radio :label="3">3串1</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="显示类型">
            <el-radio-group v-model="ruleForm.show_lx">
              <el-radio :label="1">首页优选</el-radio>
              <el-radio :label="2">近期连红</el-radio>
              <el-radio :label="3">近期爆棚</el-radio>
              <el-radio :label="4">今日热卖</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="赛事修改">
            <div v-if="ruleForm.matchList && ruleForm.matchList.length > 0">
              <div
                v-for="(match, index) in ruleForm.matchList"
                :key="index"
                style="margin-bottom: 20px; padding: 15px; border: 1px solid #e4e7ed; border-radius: 4px;"
              >
                <div style="margin-bottom: 10px; font-weight: bold;">
                  <span v-if="ruleForm.category == 1">{{ match.home_team_name }} VS {{ match.away_team_name }}</span>
                  <span v-if="ruleForm.category == 2">{{ match.away_team_name }} VS {{ match.home_team_name }}</span>
                  <span style="margin-left: 10px; color: #909399;">{{ match.competition_name }}</span>
                </div>

                <!-- 预测分类选择 -->
                <div style="margin-bottom: 15px; padding: 10px; background-color: #f8f9fa; border-radius: 4px;">
                  <div style="font-size: 14px; font-weight: 600; color: #303133; margin-bottom: 8px;">
                    预测分类：
                    <span style="font-size: 12px; color: #909399;">(共{{ predictionTypes.length }}个选项)</span>
                  </div>
                  <el-radio-group v-model="match.predictionType" size="mini" @change="handlePredictionChange(match, index)">
                    <el-radio v-for="item in predictionTypes" :key="item.id" :label="item.id">{{ item.text }}</el-radio>
                  </el-radio-group>
                  <div v-if="predictionTypes.length === 0" style="color: #f56c6c; font-size: 12px; margin-top: 5px;">
                    暂无预测分类数据
                  </div>
                </div>
                <!-- 赔率选择区域 -->
                <div v-if="match.predictionType && getMatchOdds(match).length > 0" style="margin-top: 15px; padding: 10px; background-color: #f0f9ff; border-radius: 4px;">
                  <div style="font-size: 14px; font-weight: 600; color: #303133; margin-bottom: 8px;">
                    赔率选项：
                    <span style="font-size: 12px; color: #909399;">(共{{ getMatchOdds(match).length }}个选项)</span>
                  </div>
                  <div style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 8px;">
                    <el-checkbox-button
                      v-for="(odds, oddsIndex) in getMatchOdds(match)"
                      :key="oddsIndex"
                      v-model="match.selectedOdds"
                      :label="odds"
                      class="odds-checkbox"
                    >
                      <div style="display: flex; flex-direction: column; align-items: center; gap: 3px; padding: 8px 12px;">
                        <div style="font-size: 12px; font-weight: 500; color: #606266;">{{ odds.label }}</div>
                        <div style="font-size: 14px; font-weight: 600; color: #e6a23c;">{{ odds.value }}</div>
                      </div>
                    </el-checkbox-button>
                  </div>
                  <div v-if="match.selectedOdds && match.selectedOdds.length > 0" style="margin-top: 10px;">
                    <div style="font-size: 12px; color: #67c23a; margin-bottom: 5px;">已选择：</div>
                    <div style="display: flex; flex-wrap: wrap; gap: 5px;">
                      <span
                        v-for="(selectedOdd, selectedIndex) in match.selectedOdds"
                        :key="selectedIndex"
                        style="background: #67c23a; color: white; padding: 2px 8px; border-radius: 12px; font-size: 12px;"
                      >
                        {{ selectedOdd.label }}({{ selectedOdd.value }})
                      </span>
                    </div>
                  </div>
                </div>

                <!-- 原始赔率显示（作为备用） -->
                <div v-else-if="match.odds && match.odds.length > 0" style="margin-top: 15px;">
                  <div style="font-size: 14px; font-weight: 600; color: #303133; margin-bottom: 8px;">原始赔率：</div>
                  <div style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 8px; max-width: 100%;">
                    <template v-for="(odd) in match.odds">
                      <div
                        v-for="son in odd"
                        :key="son.id"
                        :style="{
                          padding: '8px 12px',
                          backgroundColor: son.is_recommend ? '#409EFF' : '#F5F7FA',
                          color: son.is_recommend ? 'white' : '#606266',
                          border: son.is_recommend ? 'none' : '1px solid #DCDFE6',
                          borderRadius: '4px',
                          textAlign: 'center',
                          fontSize: '12px',
                          fontWeight: '500'
                        }"
                      >
                        {{ son.label }}({{ son.value }})
                      </div>
                    </template>
                  </div>
                </div>

                <!-- 无赔率数据提示 -->
                <div v-else style="margin-top: 15px; padding: 10px; background-color: #fef0f0; border-radius: 4px;">
                  <div style="font-size: 12px; color: #f56c6c;">
                    请先选择预测分类以获取赔率数据
                  </div>
                </div>

              </div>
            </div>
            <div v-else>
              <span style="color: #909399;">暂无赛事数据</span>
            </div>
            <!-- <el-button type="primary" @click="clickDelete">确认修改</el-button> -->
          </el-form-item>
          <el-form-item label="文章标题">
            <el-input v-model="ruleForm.title" />
          </el-form-item>
          <el-form-item label="文章介绍">
            <div v-if="isVisible">
              <WangEditor :content="contentData3" @submit="workVadeUpdate3" />
            </div>
          </el-form-item>
          <el-form-item label="使用数据">
            <!-- 加载状态 -->
            <div v-if="loadingUsageData" style="text-align: center; padding: 40px; background-color: #f8f9fa; border-radius: 4px; border: 1px solid #e4e7ed;">
              <i class="el-icon-loading" style="font-size: 24px; color: #409EFF; margin-right: 8px;" />
              <span style="color: #606266; font-size: 14px;">正在获取使用数据，请稍候...</span>
            </div>
            <!-- 数据展示 -->
            <div v-else-if="Object.keys(usageData).length > 0" style="max-height: 500px; overflow-y: auto; padding: 15px; background-color: #f8f9fa; border-radius: 4px; border: 1px solid #e4e7ed;">
              <div v-for="(matchData, matchId) in usageData" :key="matchId" style="margin-bottom: 20px; padding: 15px; background-color: white; border-radius: 4px; border: 1px solid #e4e7ed;">
                <div style="font-size: 16px; font-weight: bold; margin-bottom: 10px; color: #303133;">
                  {{ matchData.主队 }} VS {{ matchData.客队 }}
                </div>

                <!-- 主队战绩 -->
                <div v-if="matchData.主队战绩" style="margin-bottom: 15px;">
                  <div style="font-size: 14px; font-weight: 600; color: #606266; margin-bottom: 8px;">主队战绩：</div>
                  <div style="font-size: 13px; padding: 10px; background-color: #f0f9ff; border-radius: 4px; border-left: 4px solid #409EFF;">
                    <span style="font-weight: 500; color: #409EFF;">{{ matchData.主队 }}：</span>
                    {{ matchData.主队战绩 }}
                  </div>
                </div>

                <div v-if="matchData.主队排名" style="margin-bottom: 15px;">
                  <div style="font-size: 14px; font-weight: 600; color: #606266; margin-bottom: 8px;">主队排名：</div>
                  <div style="font-size: 13px; padding: 10px; background-color: #f0f9ff; border-radius: 4px; border-left: 4px solid #409EFF;">
                    <span style="font-weight: 500; color: #409EFF;">{{ matchData.主队 }}：</span>
                    {{ matchData.主队排名 }}
                  </div>
                </div>

                <!-- 客队战绩 -->
                <div v-if="matchData.客队战绩" style="margin-bottom: 15px;">
                  <div style="font-size: 14px; font-weight: 600; color: #606266; margin-bottom: 8px;">客队战绩：</div>
                  <div style="font-size: 13px; padding: 10px; background-color: #f0f9ff; border-radius: 4px; border-left: 4px solid #67c23a;">
                    <span style="font-weight: 500; color: #67c23a;">{{ matchData.客队 }}：</span>
                    {{ matchData.客队战绩 }}
                  </div>
                </div>

                <div v-if="matchData.客队排名" style="margin-bottom: 15px;">
                  <div style="font-size: 14px; font-weight: 600; color: #606266; margin-bottom: 8px;">客队排名：</div>
                  <div style="font-size: 13px; padding: 10px; background-color: #f0f9ff; border-radius: 4px; border-left: 4px solid #67c23a;">
                    <span style="font-weight: 500; color: #67c23a;">{{ matchData.客队 }}：</span>
                    {{ matchData.客队排名 }}
                  </div>
                </div>

                <!-- 主队上场数据 -->
                <div v-if="matchData.主队上场数据" style="margin-bottom: 15px;">
                  <div style="font-size: 14px; font-weight: 600; color: #606266; margin-bottom: 8px;">主队上场数据：</div>
                  <div style="font-size: 13px; padding: 10px; background-color: #fff7e6; border-radius: 4px; border-left: 4px solid #e6a23c;">
                    <span style="font-weight: 500; color: #e6a23c;">{{ matchData.主队 }}：</span>
                    {{ matchData.主队上场数据 }}
                  </div>
                </div>

                <!-- 客队上场数据 -->
                <div v-if="matchData.客队上场数据" style="margin-bottom: 15px;">
                  <div style="font-size: 14px; font-weight: 600; color: #606266; margin-bottom: 8px;">客队上场数据：</div>
                  <div style="font-size: 13px; padding: 10px; background-color: #fff7e6; border-radius: 4px; border-left: 4px solid #e6a23c;">
                    <span style="font-weight: 500; color: #e6a23c;">{{ matchData.客队 }}：</span>
                    {{ matchData.客队上场数据 }}
                  </div>
                </div>

                <!-- 伤停信息 -->
                <div v-if="matchData.伤停" style="margin-bottom: 15px;">
                  <div style="font-size: 14px; font-weight: 600; color: #606266; margin-bottom: 8px;">伤停信息：</div>
                  <div v-for="(injuries, team) in matchData.伤停" :key="team" style="margin-bottom: 8px;">
                    <div v-if="injuries && injuries.length > 0" style="font-size: 13px;">
                      <span style="font-weight: 500; color: #409EFF;">{{ team }}：</span>
                      <span v-for="(injury, index) in injuries" :key="index" style="margin-right: 10px;">
                        {{ injury.name }}({{ injury.reason }})
                      </span>
                    </div>
                    <div v-else style="font-size: 13px; color: #909399;">
                      <span style="font-weight: 500; color: #67c23a;">{{ team }}：</span>无伤停
                    </div>
                  </div>
                </div>

                <!-- 历史交锋 -->
                <div v-if="matchData.历史交锋 && matchData.历史交锋.length > 0" style="margin-bottom: 15px;">
                  <div style="font-size: 14px; font-weight: 600; color: #606266; margin-bottom: 8px;">历史交锋：</div>

                  <!-- 双方交战数据 -->
                  <div v-if="matchData.双方交战数据" style="margin-bottom: 10px; padding: 10px; background-color: #fff7e6; border-radius: 4px; border-left: 4px solid #e6a23c;">
                    <div style="font-size: 13px; color: #e6a23c; font-weight: 500;">
                      {{ matchData.双方交战数据 }}
                    </div>
                  </div>
                  <div v-for="(history, index) in matchData.历史交锋" :key="index" style="font-size: 13px; margin-bottom: 5px; padding: 8px; background-color: #f0f9ff; border-radius: 4px;">
                    <div style="margin-bottom: 3px;">
                      <span style="font-weight: 500;">
                        <span
                          :style="{
                            color: history.team_A_name === matchData.主队 ? '#409EFF' :
                              history.team_A_name === matchData.客队 ? '#67c23a' : '#606266',
                            fontWeight: history.team_A_name === matchData.主队 || history.team_A_name === matchData.客队 ? 'bold' : 'normal'
                          }"
                        >
                          {{ history.team_A_name }}(主队)
                        </span>
                        {{ history.fs_A }} - {{ history.fs_B }}
                        <span
                          :style="{
                            color: history.team_B_name === matchData.主队 ? '#409EFF' :
                              history.team_B_name === matchData.客队 ? '#67c23a' : '#606266',
                            fontWeight: history.team_B_name === matchData.主队 || history.team_B_name === matchData.客队 ? 'bold' : 'normal'
                          }"
                        >
                          {{ history.team_B_name }}(客队)
                        </span>
                      </span>
                    </div>
                    <div style="color: #909399; font-size: 12px;">
                      {{ history.competition_name }} | {{ history.start_play }}
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="付费内容">
            <div v-if="isVisible" style="display: flex; align-items: flex-start; gap: 10px;">
              <div style="flex: 1;">
                <WangEditor :content="contentData4" @submit="workVadeUpdate4" />
              </div>
              <el-button
                type="primary"
                size="small"
                :loading="regenerateLoading"
                :disabled="regenerateLoading"
                style="min-width: 80px;"
                @click="regenerateChargeContent"
              >
                <i v-if="!regenerateLoading" class="el-icon-refresh" />
                {{ regenerateLoading ? '生成中...' : '重新生成' }}
              </el-button>
            </div>
          </el-form-item>
          <el-form-item label="价格">
            <el-input v-model="ruleForm.price" />
          </el-form-item>
          <el-form-item label="是否付费">
            <el-radio-group v-model="ruleForm.is_free">
              <el-radio :label="1">付费</el-radio>
              <el-radio :label="2">免费</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="是否不中退">
            <el-radio-group v-model="ruleForm.no_win_back">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="2">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="是否执行红黑">
            <el-radio-group v-model="ruleForm.exec_hh">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="2">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="是否显示">
            <el-radio-group v-model="ruleForm.status">
              <el-radio :label="1">显示</el-radio>
              <el-radio :label="2">隐藏</el-radio>
            </el-radio-group>
          </el-form-item>

        </el-form>
        <div style="text-align: right;">
          <el-button @click="clickDelete">取消</el-button>
          <el-button type="primary" @click="clickConfirm(2)">审核发布</el-button>
        </div>
      </el-dialog>
    </div>
    <ExpertSelector :visible.sync="showExpertSelector" @select="handleExpertSelect" />
  </div>
</template>

<script>
import { aiRecommendList, aiRecommendAudit, additionData, expertList, getConfigList, hqOddsData, aiRecommendDelete, aiRecommendreview, zhuanjiaInfo } from '../../../libs/api'
import waves from '@/directive/waves' // waves directive
import WangEditor from '@/components/richText'
import ExpertSelector from '@/components/ExpertSelector.vue'
import axios from 'axios'
const resultStatusOptions = [
  { key: 0, display_name: '未开奖' },
  { key: 1, display_name: '中奖' },
  { key: 2, display_name: '未中奖' }
]

const saleStatusOptions = [
  { key: 0, display_name: '未开售' },
  { key: 1, display_name: '销售中' },
  { key: 2, display_name: '已停售' }
]

const passLxOptions = [
  { key: 1, display_name: '单关' },
  { key: 2, display_name: '二串1' },
  { key: 3, display_name: '三串1' }
]

const categoryOptions = [
  { value: 1, label: '足球赛事' },
  { value: 2, label: '篮球赛事' }
]

export default {
  name: 'AiSchemeList',
  components: {
    WangEditor,
    ExpertSelector
  },
  directives: { waves },
  filters: {
    resultStatusFilter(status) {
      const statusMap = {
        0: 'info',
        1: 'success',
        2: 'danger'
      }
      return statusMap[status]
    },
    resultStatusNameFilter(status) {
      const statusMap = {
        0: '未开奖',
        1: '中奖',
        2: '未中奖'
      }
      return statusMap[status]
    },
    saleStatusFilter(status) {
      const statusMap = {
        0: 'info',
        1: 'success',
        2: 'warning'
      }
      return statusMap[status]
    },
    saleStatusNameFilter(status) {
      const statusMap = {
        0: '未开售',
        1: '销售中',
        2: '已停售'
      }
      return statusMap[status]
    },
    passLxFilter(type) {
      const typeMap = {
        1: 'primary',
        2: 'success',
        3: 'warning'
      }
      return typeMap[type]
    },
    showLxFilter(type) {
      const typeMap = {
        1: 'success',
        2: 'info'
      }
      return typeMap[type]
    }
  },
  data() {
    return {
      showExpertSelector: false,
      fbAll: [{
        id: 1,
        nickname: '足球'
      }, {
        id: 2,
        nickname: '篮球'
      }],
      yOrN: [{
        id: 1,
        nickname: '是'
      }, {
        id: 2,
        nickname: '否'
      }],
      dialogTableVisible: false,
      dialogVisible: false,
      dialogTableModify: false,
      valuess: '',
      values: '',
      value: '',
      sortCard: '',
      content: '',
      dialogImageUrl: '',
      innerVisible: false,
      checkboxGroup1: [],
      checkboxGroup2: [],
      indexData: ['1.6', '1.7', '1.8'],
      indexData1: ['1.99', '1.9', '1.77'],
      tableData: [],
      rules: {},
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        title: undefined,
        result_status: undefined,
        sale_status: undefined,
        pass_lx: undefined
      },
      resultStatusOptions,
      saleStatusOptions,
      passLxOptions,
      categoryOptions,
      dialogFormVisible: false,
      currentScheme: null,
      auditDialogVisible: false,
      auditForm: {
        scheme_id: '',
        result: 'approved',
        comment: ''
      },
      editDialogVisible: false,
      isEditVisible: false,
      editContentData1: '',
      editContentData2: '',
      expertDataList: [],
      editForm: {
        id: '',
        category: '',
        expert_id: '',
        show_lx: 1,
        pass_lx: 1,
        title: '',
        free_content: '',
        charge_content: '',
        price: '',
        is_free: 1,
        no_win_back: 2,
        exec_hh: 2,
        status: 1,
        sort: 0
      },
      editRules: {
        category: [{ required: true, message: '请选择分类', trigger: 'change' }],
        expert_id: [{ required: true, message: '请选择专家', trigger: 'change' }]
      },
      // 简化的数据属性 - 只保留样式需要的
      titleData: '',
      inputName: '',
      fbData: '',
      ynData: '',
      currentPage: 1,
      totalCount: 1,
      PageSize: 5,
      pageSizes: [5, 10],
      open: false,
      modifyShow: false,
      listData: [],
      dataList: [],
      yuce: [],
      radio1: {},
      typeData: '',
      oddsDataList: [],
      max: 2,
      fanxian: [],
      oodMatchData: {},
      allOodData: [],
      ruleForm: {
        category: '',
        expert_id: '',
        show_lx: 1,
        pass_lx: 1,
        title: '',
        free_content: '',
        charge_content: '',
        price: '',
        is_free: 1,
        no_win_back: 2,
        exec_hh: 2,
        status: 1,
        sort: '',
        matches: '',
        yuce: ''
      },
      options: [{
        valuess: 1,
        label: '足球赛事'
      }, {
        valuess: 2,
        label: '篮球赛事'
      }],
      checkboxGroup4: [],
      checkboxGroup5: [],
      inputData: '',
      isVisible: false,
      isVisible1: false,
      contentData1: '',
      contentData2: '',
      contentData3: '',
      contentData4: '',
      selectedOdds: [], // 存储每个赛事选中的赔率
      regenerateLoading: false, // 重新生成按钮加载状态
      predictionTypes: [], // 预测分类列表
      usageData: {}, // 存储使用数据
      loadingUsageData: false, // 使用数据加载状态
      review: 0,
      titleGenerateTimer: null // 标题生成防抖定时器
    }
  },
  watch: {
    // 监听赛事列表变化，自动生成标题（仅监听数量变化）
    'ruleForm.matchList.length': {
      handler(newLength, oldLength) {
        // 只有当赛事数量发生变化时才生成标题
        if (newLength > 0 && this.ruleForm.expert_id && newLength !== oldLength) {
          // 延迟执行，避免频繁触发
          this.$nextTick(() => {
            this.generateTitleForScheme()
          })
        }
      }
    },
    // 监听弹窗打开状态，打开时生成标题
    dialogFormVisible: {
      handler(isVisible) {
        if (isVisible && this.ruleForm.expert_id && this.ruleForm.matchList && this.ruleForm.matchList.length > 0) {
          // 弹窗打开时，延迟生成标题
          setTimeout(() => {
            this.generateTitleForScheme()
          }, 500)
        }
      }
    }
  },
  created() {
    this.getExpertList()
    this.getList()
    this.getConfigListData()
  },
  beforeDestroy() {
    // 清理定时器
    if (this.titleGenerateTimer) {
      clearTimeout(this.titleGenerateTimer)
    }
  },
  methods: {
    // 标题生成相关函数
    /**
     * 根据专家ID和赛事信息生成标题
     * @param {string} expertId - 专家ID
     * @param {Array} matchList - 赛事信息列表
     * @param {number} lotLx - 预测分类（1,2,3）
     * @returns {Promise<string>} 生成的标题
     */
    async generateTitleByExpert(expertId, matchList, lotLx = 1) {
      try {
        // 获取专家信息
        const res = await zhuanjiaInfo({ expert_id: expertId })
        const expertData = res.data

        if (!expertData) {
          console.warn('专家信息不存在')
          return this.ruleForm.title || '暂无标题'
        }

        // 根据预测分类选择不同的标题模板
        let template = ''
        if (lotLx === 1) {
          template = expertData.title
        } else if (lotLx === 2) {
          template = expertData.title2
        } else if (lotLx === 3) {
          template = expertData.title1
        } else {
          template = expertData.title // 默认使用title
        }

        if (!template) {
          console.warn(`专家信息中不存在对应的标题模板，lot_lx: ${lotLx}`)
          return this.ruleForm.title || '暂无标题'
        }

        // 使用选择的标题模板生成标题
        const generatedTitle = this.generateTitleFromTemplate(template, matchList)

        console.log('专家标题生成成功:', {
          expertId,
          expertName: expertData.nickname,
          lotLx,
          selectedTemplate: template,
          generatedTitle
        })

        return generatedTitle
      } catch (error) {
        console.error('获取专家信息失败:', error)
        return this.ruleForm.title || '暂无标题'
      }
    },

    /**
     * 根据专家ID和赛事信息生成文章介绍
     * @param {string} expertId - 专家ID
     * @param {Array} matchList - 赛事信息列表
     * @param {number} lotLx - 预测分类（1,2,3）
     * @returns {Promise<string>} 生成的文章介绍
     */
    async generateIntroductionByExpert(expertId, matchList, lotLx = 1) {
      try {
        // 获取专家信息
        const res = await zhuanjiaInfo({ expert_id: expertId })
        const expertData = res.data

        if (!expertData) {
          console.warn('专家信息不存在')
          return this.ruleForm.free_content || ''
        }

        // 使用 free_content 作为模板
        const template = expertData.free_content

        if (!template) {
          console.warn('专家信息中没有文章介绍模板')
          return this.ruleForm.free_content || ''
        }

        // 使用文章介绍模板生成内容
        const generatedIntroduction = this.generateIntroductionFromTemplate(template, matchList)

        console.log('文章介绍生成成功:', {
          expertId,
          expertName: expertData.nickname,
          lotLx,
          generatedIntroduction: generatedIntroduction.substring(0, 50) + '...'
        })

        return generatedIntroduction
      } catch (error) {
        console.error('获取专家信息失败:', error)
        return this.ruleForm.free_content || ''
      }
    },

    /**
     * 根据模板字符串和赛事信息生成文章介绍
     * @param {string} template - 文章介绍模板字符串
     * @param {Array} matchList - 赛事信息列表
     * @returns {string} 生成的文章介绍
     */
    generateIntroductionFromTemplate(template, matchList) {
      if (!template || !matchList || matchList.length === 0) {
        return template || ''
      }

      let result = template

      // 如果只有一场比赛，将"串关"替换为"单关"
      if (matchList.length === 1) {
        result = result.replace(/串关/g, '单关')
      }

      // 根据比赛类型替换术语
      const matchType = matchList[0]?.match_lx || 1 // 默认足球
      if (matchType === 1) {
        // 足球：大小球、让球
        result = result.replace(/大小分/g, '大小球')
        result = result.replace(/让分/g, '让球')
        // 足球：替换运动类型和emoji
        result = result.replace(/篮球/g, '足球')
        result = result.replace(/🏀/g, '⚽️')
      } else if (matchType === 2) {
        // 篮球：大小分、让分
        result = result.replace(/大小球/g, '大小分')
        result = result.replace(/让球/g, '让分')
        // 篮球：替换运动类型和emoji
        result = result.replace(/足球/g, '篮球')
        result = result.replace(/⚽️/g, '🏀')
      }

      // 替换主队 VS 客队的模式
      const vsPattern = /主队\s*VS\s*客队/g
      let matchIndex = 0
      const maxReplacements = matchList.length

      result = result.replace(vsPattern, () => {
        if (matchIndex < maxReplacements) {
          const match = matchList[matchIndex]
          matchIndex++
          return `${match.home_team_name} VS ${match.away_team_name}`
        }
        return '主队 VS 客队' // 如果赛事信息不够，保持原样
      })

      // 去掉多余的占位符，根据实际比赛数量
      if (matchList.length === 1) {
        // 单场比赛：去掉所有剩余的占位符
        result = result.replace(/(\+\s*主队\s*VS\s*客队\s*)+/g, '')
      } else if (matchList.length === 2) {
        // 两场比赛：去掉最后一个占位符
        result = result.replace(/\+\s*主队\s*VS\s*客队\s*$/, '')
        result = result.replace(/\+\s*主队\s*VS\s*客队\s*\+/, '+')
      }

      return result
    },

    /**
     * 根据模板字符串和赛事信息生成标题
     * @param {string} template - 标题模板字符串
     * @param {Array} matchList - 赛事信息列表
     * @returns {string} 生成的标题
     */
    generateTitleFromTemplate(template, matchList) {
      if (!template || !matchList || matchList.length === 0) {
        return template || '暂无标题'
      }

      let result = template

      // 如果只有一场比赛，将"串关"替换为"单关"
      if (matchList.length === 1) {
        result = result.replace(/串关/g, '单关')
      }

      // 根据比赛类型替换术语
      const matchType = matchList[0]?.match_lx || 1 // 默认足球
      if (matchType === 1) {
        // 足球：大小球、让球
        result = result.replace(/大小分/g, '大小球')
        result = result.replace(/让分/g, '让球')
        // 足球：替换运动类型和emoji
        result = result.replace(/篮球/g, '足球')
        result = result.replace(/🏀/g, '⚽️')
      } else if (matchType === 2) {
        // 篮球：大小分、让分
        result = result.replace(/大小球/g, '大小分')
        result = result.replace(/让球/g, '让分')
        // 篮球：替换运动类型和emoji
        result = result.replace(/足球/g, '篮球')
        result = result.replace(/⚽️/g, '🏀')
      }

      // 替换主队 VS 客队的模式
      const vsPattern = /主队\s*VS\s*客队/g
      let matchIndex = 0
      const maxReplacements = matchList.length

      result = result.replace(vsPattern, () => {
        if (matchIndex < maxReplacements) {
          const match = matchList[matchIndex]
          matchIndex++
          return `${match.home_team_name} VS ${match.away_team_name}`
        }
        return '主队 VS 客队' // 如果赛事信息不够，保持原样
      })

      // 去掉多余的占位符，根据实际比赛数量
      if (matchList.length === 1) {
        // 单场比赛：去掉所有剩余的占位符
        result = result.replace(/(\+\s*主队\s*VS\s*客队\s*)+/g, '')
      } else if (matchList.length === 2) {
        // 两场比赛：去掉最后一个占位符
        result = result.replace(/\+\s*主队\s*VS\s*客队\s*$/, '')
        result = result.replace(/\+\s*主队\s*VS\s*客队\s*\+/, '+')
      }

      return result
    },

    /**
     * 为当前方案生成标题（带防抖）
     */
    generateTitleForScheme() {
      // 清除之前的定时器
      if (this.titleGenerateTimer) {
        clearTimeout(this.titleGenerateTimer)
      }

      // 设置防抖延迟
      this.titleGenerateTimer = setTimeout(async() => {
        await this.doGenerateTitle()
      }, 500) // 500ms防抖延迟
    },

    /**
     * 执行标题生成
     */
    async doGenerateTitle() {
      // 检查是否有专家ID和赛事列表
      if (!this.ruleForm.expert_id || !this.ruleForm.matchList || this.ruleForm.matchList.length === 0) {
        console.log('缺少专家ID或赛事列表，跳过标题生成')
        return
      }

      try {
        // 获取当前预测分类（从第一个赛事获取，假设所有赛事使用相同的预测分类）
        const currentLotLx = this.ruleForm.matchList[0]?.predictionType || 1

        console.log('开始为方案生成标题和文章介绍...', {
          expertId: this.ruleForm.expert_id,
          matchCount: this.ruleForm.matchList.length,
          lotLx: currentLotLx
        })

        // 生成标题
        const generatedTitle = await this.generateTitleByExpert(this.ruleForm.expert_id, this.ruleForm.matchList, currentLotLx)

        // 更新标题
        this.ruleForm.title = generatedTitle

        console.log('方案标题已更新:', generatedTitle)

        // 生成文章介绍
        const generatedIntroduction = await this.generateIntroductionByExpert(this.ruleForm.expert_id, this.ruleForm.matchList, currentLotLx)

        // 更新文章介绍
        this.ruleForm.free_content = generatedIntroduction
        this.contentData3 = generatedIntroduction

        console.log('方案文章介绍已更新:', generatedIntroduction.substring(0, 50) + '...')

        // 显示成功提示
        this.$message({
          type: 'success',
          message: '标题和文章介绍已自动生成！',
          duration: 2000
        })
      } catch (error) {
        console.error('生成方案标题或文章介绍失败:', error)
        this.$message({
          type: 'warning',
          message: '生成失败，请手动输入',
          duration: 3000
        })
      }
    },

    getList() {
      this.listLoading = true
      const params = {
        page: this.currentPage,
        page_size: this.PageSize,
        review: this.review
      }

      aiRecommendList(params).then(response => {
        this.list = response.data.list
        this.tableData = response.data.list
        this.alltabData = response.data.list
        this.totalCount = response.data.total

        // 为没有标题的项自动生成标题

        this.listLoading = false
      }).catch(() => {
        this.listLoading = false
      })
    },
    handleFilter() {
      this.currentPage = 1
      this.getList()
    },
    handleReviewChange() {
      this.currentPage = 1
      this.getList()
    },
    resetFilter() {
      this.review = 0
      this.currentPage = 1
      this.getList()
    },
    handleView(row) {
      this.currentScheme = row
      this.dialogFormVisible = true

      // 弹窗打开后生成标题
      this.$nextTick(() => {
        this.generateTitleForScheme()
      })
    },
    closeDialog() {
      this.dialogFormVisible = false
      this.currentScheme = null
      // 关闭弹窗时重新加载列表
      this.getList()
    },
    handleAudit(row) {
      this.auditForm.scheme_id = row.id
      this.auditForm.result = 'approved'
      this.auditDialogVisible = true
    },
    submitAudit() {
      const params = {
        id: this.auditForm.scheme_id,
        status: this.auditForm.result === 'approved' ? 1 : 2, // 1: 通过, 2: 拒绝
        comment: this.auditForm.comment
      }

      aiRecommendAudit(params).then(() => {
        // 如果审核通过，则发布方案
        if (this.auditForm.result === 'approved') {
          this.publishScheme(this.auditForm.scheme_id)
        } else {
          this.$message({
            message: '审核完成',
            type: 'success'
          })
          this.auditDialogVisible = false
          this.dialogFormVisible = false
          this.currentScheme = null
          this.getList() // 刷新列表
        }
      }).catch(() => {
        this.$message({
          message: '审核失败',
          type: 'error'
        })
      })
    },
    publishScheme(schemeId) {
      // 找到对应的方案数据
      const scheme = this.list.find(item => item.id === schemeId)
      if (!scheme) {
        this.$message({
          message: '方案数据不存在',
          type: 'error'
        })
        return
      }

      const publishParams = {
        category: scheme.category,
        expert_id: scheme.expert_id,
        show_lx: scheme.show_lx,
        pass_lx: scheme.pass_lx,
        title: scheme.title,
        free_content: scheme.free_content || '',
        charge_content: scheme.charge_content || '',
        price: scheme.price,
        is_free: scheme.is_free,
        no_win_back: scheme.no_win_back,
        exec_hh: scheme.exec_hh,
        status: 1, // 发布状态
        sort: scheme.sort || 0,
        matches: JSON.stringify(scheme.matchList || []),
        sf_pt: 2 // 标识为AI方案
      }

      additionData(publishParams).then(() => {
        this.$message({
          message: '审核通过并发布成功',
          type: 'success'
        })
        this.auditDialogVisible = false
        this.dialogFormVisible = false
        this.currentScheme = null
        this.getList() // 刷新列表
      }).catch(() => {
        this.$message({
          message: '发布失败',
          type: 'error'
        })
      })
    },
    getChargeContent(chargeContent) {
      try {
        const content = JSON.parse(chargeContent)
        const data = content.data || chargeContent

        // 根据比赛类型替换"数字+球"为"数字+分"
        return this.replaceBallToScore(data)
      } catch (e) {
        return this.replaceBallToScore(chargeContent)
      }
    },

    /**
     * 根据比赛类型替换"数字+球"为"数字+分"
     * @param {string} content - 内容字符串
     * @returns {string} 替换后的内容
     */
    replaceBallToScore(content) {
      if (!content) return content

      // 获取当前比赛类型，默认足球
      const matchType = this.ruleForm.matchList && this.ruleForm.matchList.length > 0
        ? this.ruleForm.matchList[0]?.match_lx || 1
        : 1

      // 如果是篮球，替换"数字+球"为"数字+分"
      if (matchType === 2) {
        // 匹配模式：数字+球（包括各种可能的格式）
        const ballPattern = /(\d+(?:\.\d+)?)\s*球/g
        return content.replace(ballPattern, '$1分')
      }

      return content
    },
    // 编辑相关方法
    handleEdit(row) {
      this.editForm = {

        category: row.category,
        expert_id: row.expert_id,
        show_lx: row.show_lx,
        pass_lx: row.pass_lx,
        title: row.title || '',
        free_content: row.free_content || '',
        charge_content: row.charge_content || '',
        price: row.price,
        is_free: row.is_free,
        no_win_back: row.no_win_back,
        exec_hh: row.exec_hh,
        status: row.status,
        sort: row.sort || 0
      }
      this.editContentData1 = row.free_content || ''

      this.editContentData2 = row.charge_content || ''
      this.isEditVisible = true
      this.editDialogVisible = true
    },
    closeEditForm() {
      this.editDialogVisible = false
      this.isEditVisible = false
      this.editContentData1 = ''
      this.editContentData2 = ''
      this.$refs.editForm.resetFields()
    },
    handleSelectChange(value) {
      console.log('分类改变:', value)
    },
    workVadeUpdateEdit1(content) {
      this.editForm.free_content = content
    },
    workVadeUpdateEdit2(content) {
      this.editForm.charge_content = content
    },
    submitEdit() {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          // 这里调用更新接口
          // const params = {
          //   id: this.editForm.id,
          //   category: this.editForm.category,
          //   expert_id: this.editForm.expert_id,
          //   show_lx: this.editForm.show_lx,
          //   pass_lx: this.editForm.pass_lx,
          //   title: this.editForm.title,
          //   free_content: this.editForm.free_content,
          //   charge_content: this.editForm.charge_content,
          //   price: this.editForm.price,
          //   is_free: this.editForm.is_free,
          //   no_win_back: this.editForm.no_win_back,
          //   exec_hh: this.editForm.exec_hh,
          //   status: this.editForm.status,
          //   sort: this.editForm.sort
          // }

          // 调用更新接口（这里需要根据实际API调整）
          this.$message({
            message: '编辑功能待实现API接口',
            type: 'info'
          })

          // 临时关闭对话框
          this.closeEditForm()
          this.getList()
        }
      })
    },
    getExpertList() {
      expertList({
        page: 1,
        limit: 1000
      }).then(res => {
        this.expertDataList = res.data.list
      })
    },
    // 获取配置列表数据
    getConfigListData() {
      getConfigList({}).then(res => {
        console.log('获取配置数据:', res)
        if (res.data && res.data.lotLxList) {
          this.predictionTypes = res.data.lotLxList
          console.log('预测分类列表:', this.predictionTypes)
        } else {
          console.warn('未找到预测分类数据，使用默认数据')
          // 使用默认的预测分类数据
          this.predictionTypes = [
            { id: 1, text: '胜平负' },
            { id: 2, text: '让球胜平负' },
            { id: 3, text: '总进球' },
            { id: 4, text: '比分' },
            { id: 5, text: '半全场' },
            { id: 6, text: '竞彩' }
          ]
        }
      }).catch(error => {
        console.error('获取配置数据失败:', error)
        // API 调用失败时使用默认数据
        this.predictionTypes = [
          { id: 1, text: '胜平负' },
          { id: 2, text: '让球胜平负' },
          { id: 3, text: '总进球' },
          { id: 4, text: '比分' },
          { id: 5, text: '半全场' },
          { id: 6, text: '竞彩' }
        ]
      })
    },
    // 处理预测分类变更
    handlePredictionChange(match, matchIndex) {
      console.log('预测分类变更触发:', {
        match: match,
        matchIndex: matchIndex,
        predictionType: match.predictionType,
        matchListLength: this.ruleForm.matchList ? this.ruleForm.matchList.length : 0
      })

      // 清空之前选中的赔率
      if (this.ruleForm.matchList && this.ruleForm.matchList[matchIndex]) {
        this.ruleForm.matchList[matchIndex].selectedOdds = []
        console.log('已清空选中赔率')
      }

      // 强制更新视图
      this.$forceUpdate()

      // 获取对应预测分类的赔率数据
      if (match.predictionType) {
        this.fetchOddsFromAPI(match, match.predictionType)
      }

      // 触发标题生成（带防抖）
      this.generateTitleForScheme()
    },
    // 获取赔率数据
    fetchOddsFromAPI(match, predictionType) {
      if (!match.match_id) {
        console.warn('赛事ID不存在，无法获取赔率')
        return
      }

      console.log('开始获取赔率数据:', {
        match_id: match.match_id,
        lx: 1, // 足球
        lot_lx: predictionType
      })

      hqOddsData({
        match_id: match.match_id,
        lx: match.match_lx, // 足球
        lot_lx: predictionType
      }).then(res => {
        console.log('获取赔率数据成功:', res)
        if (res.data && res.data.odds) {
          // 缓存赔率数据
          if (!match.cachedOdds) {
            this.$set(match, 'cachedOdds', {})
          }

          let oddsData = []
          if (predictionType === 1) {
            // 胜平负数据是二维数组，需要合并
            if (Array.isArray(res.data.odds) && res.data.odds.length > 0) {
              if (Array.isArray(res.data.odds[0])) {
                // 二维数组，需要合并
                oddsData = res.data.odds.flat()
              } else {
                // 一维数组
                oddsData = res.data.odds
              }
            }
          } else {
            // 其他类型（包括竞彩）的处理
            if (Array.isArray(res.data.odds) && res.data.odds.length > 0) {
              if (Array.isArray(res.data.odds[0])) {
                // 二维数组，根据hqinformation的逻辑，直接使用整个数组
                oddsData = res.data.odds.flat()
              } else {
                // 一维数组
                oddsData = res.data.odds
              }
            }
          }

          console.log('处理后的赔率数据:', oddsData)

          // 转换数据格式
          const formattedOdds = oddsData.map(item => ({
            label: item.label || item.name || '未知',
            value: item.value || item.odds || '-',
            is_recommend: false
          }))

          this.$set(match.cachedOdds, predictionType, formattedOdds)
          console.log('赔率数据已缓存:', formattedOdds)

          // 强制更新视图以显示新的赔率数据
          this.$forceUpdate()
        }
      }).catch(error => {
        console.error('获取赔率数据失败:', error)
      })
    },
    // 获取赛事的赔率选项
    getMatchOdds(match) {
      if (!match.predictionType) return []

      // 如果已经有缓存的赔率数据，直接返回
      if (match.cachedOdds && match.cachedOdds[match.predictionType]) {
        return match.cachedOdds[match.predictionType]
      }

      // 使用本地数据作为备选方案
      const oddsData = this.getLocalOddsData(match, match.predictionType)

      // 异步获取API数据
      this.fetchOddsFromAPI(match, match.predictionType)

      return oddsData
    },
    // 获取本地赔率数据
    getLocalOddsData(match, predictionType) {
      const oddsData = []

      if (predictionType === 1) { // 胜平负
        const had = match.had || {}
        oddsData.push(
          { label: '胜', value: had.h || '-', is_recommend: false },
          { label: '平', value: had.d || '-', is_recommend: false },
          { label: '负', value: had.a || '-', is_recommend: false }
        )
      } else if (predictionType === 2) { // 让球胜平负
        const hhad = match.hhad || {}
        oddsData.push(
          { label: '让球胜', value: hhad.h || '-', is_recommend: false },
          { label: '让球平', value: hhad.d || '-', is_recommend: false },
          { label: '让球负', value: hhad.a || '-', is_recommend: false }
        )
      } else if (predictionType === 3) { // 总进球
        const ttg = match.ttg || {}
        oddsData.push(
          { label: '0球', value: ttg.s0 || '-', is_recommend: false },
          { label: '1球', value: ttg.s1 || '-', is_recommend: false },
          { label: '2球', value: ttg.s2 || '-', is_recommend: false },
          { label: '3球', value: ttg.s3 || '-', is_recommend: false },
          { label: '4球', value: ttg.s4 || '-', is_recommend: false },
          { label: '5球', value: ttg.s5 || '-', is_recommend: false },
          { label: '6球+', value: ttg.s6 || '-', is_recommend: false }
        )
      } else if (predictionType === 4) { // 比分
        const crs = match.crs || {}
        oddsData.push(
          { label: '1:0', value: crs.h1_0 || '-', is_recommend: false },
          { label: '2:0', value: crs.h2_0 || '-', is_recommend: false },
          { label: '2:1', value: crs.h2_1 || '-', is_recommend: false },
          { label: '0:1', value: crs.a0_1 || '-', is_recommend: false },
          { label: '0:2', value: crs.a0_2 || '-', is_recommend: false },
          { label: '平局', value: crs.d || '-', is_recommend: false }
        )
      } else if (predictionType === 5) { // 半全场
        const hafu = match.hafu || {}
        oddsData.push(
          { label: '胜胜', value: hafu.hh || '-', is_recommend: false },
          { label: '胜平', value: hafu.hd || '-', is_recommend: false },
          { label: '胜负', value: hafu.ha || '-', is_recommend: false },
          { label: '平胜', value: hafu.dh || '-', is_recommend: false },
          { label: '平平', value: hafu.dd || '-', is_recommend: false },
          { label: '平负', value: hafu.da || '-', is_recommend: false },
          { label: '负胜', value: hafu.ah || '-', is_recommend: false },
          { label: '负平', value: hafu.ad || '-', is_recommend: false },
          { label: '负负', value: hafu.aa || '-', is_recommend: false }
        )
      }

      return oddsData
    },
    // 转换赛事数据为提交格式
    convertMatchDataForSubmit(matchList) {
      return matchList.map(match => {
        const matchData = {
          id: match.id || 0,
          recommend_id: match.recommend_id || 0,
          expert_id: this.ruleForm.expert_id,
          match_id: match.match_id,
          match_lx: match.match_lx,
          lottery_id: match.lottery_id || 1, // 默认值，后面会根据是否修改预测分类来更新
          lottery_tag: match.lottery_tag || '竞彩',
          lotty_result: match.lotty_result,
          create_time: match.create_time || new Date().toISOString().slice(0, 19).replace('T', ' '),
          update_time: match.update_time || new Date().toISOString().slice(0, 19).replace('T', ' '),
          status: match.status || 1,
          status_name: match.status_name || '',
          competition_name: match.competition_name,
          away_team_name: match.away_team_name,
          home_team_name: match.home_team_name,
          match_time: match.match_time,
          lot_lx: match.lot_lx ? match.lot_lx : 1, // 默认值，后面会根据是否修改预测分类来更新
          // 处理赔率数据
          odds: [],
          all_odds: {},
          selected_odds: {}
        }

        // 判断是否修改了预测分类
        const hasModifiedPrediction = match.predictionType !== null && match.predictionType !== undefined

        if (hasModifiedPrediction) {
          // 如果修改了预测分类，使用新的数据格式
          console.log('使用修改后的预测分类数据:', match.predictionType)
          // 使用预测分类作为 lot_lx 和 lottery_id
          matchData.lot_lx = match.predictionType
          matchData.lottery_id = match.predictionType
          // 获取该预测分类的所有赔率数据
          let allOdds = []
          if (match.cachedOdds && match.cachedOdds[match.predictionType]) {
            allOdds = match.cachedOdds[match.predictionType]
          } else {
            // 使用本地数据
            allOdds = this.getLocalOddsData(match, match.predictionType)
          }

          // 构建 odds 数组（二维数组格式）- 包含所有赔率，标记选中的
          const oddsWithRecommend = allOdds.map(odd => {
            const isSelected = match.selectedOdds && match.selectedOdds.some(selectedOdd =>
              selectedOdd.label === odd.label && selectedOdd.value === odd.value
            )
            return {
              label: odd.label,
              value: odd.value,
              is_recommend: isSelected // 选中的赔率标记为推荐
            }
          })

          matchData.odds = [oddsWithRecommend]

          // 构建 all_odds（所有赔率）
          matchData.all_odds = {
            matchId: match.match_id,
            odds: allOdds.map(odd => ({
              label: odd.label,
              value: odd.value,
              is_recommend: false
            }))
          }

          // 构建 selected_odds（选中的赔率）
          if (match.selectedOdds && match.selectedOdds.length > 0) {
            matchData.selected_odds = {
              matchId: match.match_id,
              odds: match.selectedOdds.map(odd => ({
                label: odd.label,
                value: odd.value,
                is_recommend: true
              }))
            }
          } else {
            matchData.selected_odds = {
              matchId: match.match_id,
              odds: []
            }
          }
        } else {
          // 如果没有修改预测分类，使用原来的数据格式
          console.log('使用原来的数据格式')
          matchData.odds = match.odds || []
          matchData.all_odds = match.all_odds || {}
          matchData.selected_odds = match.selected_odds || {}
        }

        console.log('转换后的赛事数据:', matchData)
        return matchData
      })
    },
    // 简化的方法 - 只保留必要的样式和基本功能
    handleExpertSelect(v) {
      this.ruleForm.expert_id = v.id

      // 专家选择后自动生成标题（带防抖）
      this.generateTitleForScheme()
    },
    topChange(v) {
      if (v.if_top === '0') {
        v.if_top = '1'
      } else {
        v.if_top = '0'
      }
    },
    handleChange() {
      this.getList()
    },
    handleChangeType() {
      this.getList()
    },
    handleChangeYesOrNo() {
      this.getList()
    },
    searchExpert() {
      this.getList()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.getList()
    },
    handleSizeChange(val) {
      this.PageSize = val
      this.currentPage = 1
      this.getList()
    },
    handleButtonAdd() {
      this.dialogTableVisible = true
    },
    clickDelete() {
      this.dialogTableModify = false
      this.dialogTableVisible = false

      // 重置表单到默认值
      this.ruleForm = {
        category: '',
        expert_id: '',
        show_lx: 1,
        pass_lx: 1,
        title: '',
        free_content: '',
        charge_content: '',
        price: '',
        is_free: 1,
        no_win_back: 2,
        exec_hh: 2,
        status: 1,
        sort: '',
        matches: '',
        yuce: ''
      }
    },
    handleButton1Click(row) {
      // 填充表单数据
      this.ruleForm = {
        id: row.id,
        category: row.category,
        expert_id: row.expert_id,
        show_lx: row.show_lx,
        pass_lx: row.pass_lx,
        title: row.title || '',
        free_content: row.free_content || '',
        charge_content: row.charge_content || '',
        price: row.price || '',
        is_free: 1, // 始终使用默认值：付费
        no_win_back: 1, // 使用数据库值，如果为空则使用默认值
        exec_hh: 2, // 始终使用默认值：否
        status: row.status,
        sort: row.sort || '',
        matchList: row.matchList || [],
        field: row.field || ''
      }

      // 初始化选中赔率状态 - 适配新的数据结构
      // 为每个赛事添加预测分类属性
      if (this.ruleForm.matchList && this.ruleForm.matchList.length > 0) {
        this.ruleForm.matchList.forEach(match => {
          if (!match.predictionType) {
            this.$set(match, 'predictionType', null)
          }
          if (!match.selectedOdds) {
            this.$set(match, 'selectedOdds', [])
          }
        })
      }

      // 先关闭编辑器，确保重新渲染
      this.isVisible = false

      // 使用 nextTick 确保 DOM 更新后再设置内容
      this.$nextTick(() => {
        this.contentData3 = row.free_content || ''
        this.contentData4 = this.parseChargeContent(row.charge_content)
        this.isVisible = true
        this.dialogTableModify = true

        // 获取赔率数据
        const matchIds = (this.ruleForm.matchList || []).map(match => match.match_id).filter(id => id)
        console.log('准备获取赔率数据，赛事分类:', this.ruleForm.category, '赛事IDs:', matchIds)
        if (matchIds.length > 0) {
          this.loadingUsageData = true
          this.getMatchesOdds(this.ruleForm.category, matchIds)
            .then(response => {
              console.log('API响应:', response)

              // 检查响应结构
              if (response && response.data) {
                const oddsData = response.data
                console.log('赔率数据:', oddsData)
                console.log('数据结构分析:', Object.keys(oddsData))

                // 保存使用数据，排除指数部分
                this.usageData = {}
                Object.keys(oddsData).forEach(matchId => {
                  const matchData = oddsData[matchId]
                  console.log(`赛事${matchId}的数据字段:`, Object.keys(matchData))
                  console.log(`赛事${matchId}的完整数据:`, matchData)

                  // 计算双方交战数据
                  const matchStats = this.calculateMatchStats(matchData.历史交锋, matchData.主队, matchData.客队)

                  // 使用正确的字段名
                  this.usageData[matchId] = {
                    主队: matchData.主队,
                    客队: matchData.客队,
                    主队战绩: matchData.主队战绩,
                    客队战绩: matchData.客队战绩,
                    主队排名: matchData.主队排名,
                    客队排名: matchData.客队排名,
                    主队上场数据: matchData.主队上场数据,
                    客队上场数据: matchData.客队上场数据,
                    伤停: matchData.伤停,
                    历史交锋: matchData.历史交锋,
                    双方交战数据: matchStats
                  }
                })
                console.log('保存的使用数据:', this.usageData)
                // 强制更新视图
                this.$forceUpdate()
              } else {
                console.error('API响应格式不正确:', response)
              }
              this.loadingUsageData = false
            })
            .catch(error => {
              console.error('获取赔率数据失败:', error)
              this.loadingUsageData = false
            })
        } else {
          console.log('没有找到有效的赛事ID')
        }

        // 延迟生成标题，确保数据完全加载
        setTimeout(() => {
          this.generateTitleForScheme()
        }, 1000)
      })
    },
    handleButton2Click(row) {
      this.$confirm('此操作将永久删除该推荐, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 调用删除接口
        aiRecommendDelete({ id: row.id }).then(response => {
          this.$message({
            message: '删除成功',
            type: 'success'
          })
          this.getList() // 刷新列表
        }).catch(error => {
          this.$message({
            message: '删除失败',
            type: 'error'
          })
          console.error('删除失败:', error)
        })
      }).catch(() => {
        // 用户取消删除
      })
    },
    modifyTap(row) {
      this.modifyShow = true
    },
    changeData(item) {
      console.log(item)
    },
    closeForm() {
      this.dialogTableVisible = false
    },
    closeFormData() {
      this.innerVisible = false
    },
    modifyForm() {
      this.dialogTableModify = false
      this.isVisible = false
      // 关闭弹窗时重新加载列表
      this.getList()
    },
    selectChangeExpert() { },
    workVadeUpdate1(content) {
      this.ruleForm.free_content = content
    },
    workVadeUpdate2(content) {
      // 直接保存内容，不包装成 JSON
      this.ruleForm.charge_content = content
    },
    workVadeUpdate3(content) {
      this.ruleForm.free_content = content
    },
    workVadeUpdate4(content) {
      // 直接保存内容，不包装成 JSON
      this.ruleForm.charge_content = content
    },

    // 将选中的赔率数据转换为 matchList 格式
    convertToMatchList(matches, selectedOdds) {
      return matches.map((match, index) => {
        const matchData = {
          id: match.id || 0,
          recommend_id: 0, // 新增时为0，修改时使用实际ID
          expert_id: this.ruleForm.expert_id,
          match_id: match.match_id || match.id,
          match_lx: 1,
          lottery_id: 1,
          lottery_tag: match.lottery_tag || '竞彩',
          lotty_result: 0,
          create_time: new Date().toISOString().slice(0, 19).replace('T', ' '),
          update_time: new Date().toISOString().slice(0, 19).replace('T', ' '),
          odds: [],
          status: 1,
          status_name: '',
          competition_name: match.competition_name,
          away_team_name: match.away_team_name,
          home_team_name: match.home_team_name,
          match_time: match.match_time
        }

        // 处理赔率数据 - 适配新的后端数据结构
        if (match.odds && Array.isArray(match.odds)) {
          // 后端数据 odds 字段已经是二维数组格式
          matchData.odds = match.odds.map((oddsGroup, groupIndex) => {
            return oddsGroup.map(odd => {
              // 检查这个赔率是否被选中
              const isSelected = selectedOdds[index] && selectedOdds[index].some(selectedOdd =>
                selectedOdd.label === odd.label && selectedOdd.value === odd.value
              )
              return {
                index: odd.index,
                is_recommend: isSelected || odd.is_recommend || false,
                is_hit: odd.is_hit || false,
                label: odd.label,
                value: odd.value
              }
            })
          })
        } else {
          // 如果没有 odds 数据，初始化为空数组
          matchData.odds = []
        }

        return matchData
      })
    },
    clickConfirm(type) {
      const that = this

      if (type === 2) {
        // 修改操作 - 保持编辑器打开状态

        // 二次确认对话框
        this.$confirm('确定要审核并发布此方案吗？', '审核发布确认', {
          confirmButtonText: '确定发布',
          cancelButtonText: '取消',
          type: 'warning',
          dangerouslyUseHTMLString: false
        }).then(() => {
          // 用户确认后执行发布操作
          this.executePublish()
        }).catch(() => {
          // 用户取消操作
          this.$message({
            type: 'info',
            message: '已取消发布'
          })
        })
      } else {
        // 新增操作
        this.isVisible1 = false

        // 转换数据格式
        const matchListData = this.convertToMatchList(this.fanxians || [], [])

        // 如果没有标题，自动生成
        let title = this.ruleForm.title
        if (!title && matchListData.length > 0) {
          title = this.generateSchemeTitle(matchListData)
        }

        additionData({
          category: this.ruleForm.category,
          expert_id: this.ruleForm.expert_id,
          show_lx: this.ruleForm.show_lx,
          pass_lx: this.ruleForm.pass_lx,
          title: title,
          free_content: this.ruleForm.free_content,
          charge_content: this.ruleForm.charge_content,
          price: this.ruleForm.price,
          is_free: this.ruleForm.is_free,
          no_win_back: this.ruleForm.no_win_back,
          exec_hh: this.ruleForm.exec_hh,
          status: this.ruleForm.status,
          sort: this.ruleForm.sort,
          matches: JSON.stringify(matchListData),
          sf_pt: 2
        }).then(res => {
          console.log(res)

          if (res.code !== 1) {
            that.$message({
              type: 'error',
              message: res.msg
            })
            return false
          }
          that.dialogTableVisible = false
          Object.assign(this.ruleForm, {
            category: '',
            expert_id: '',
            show_lx: 1,
            pass_lx: 1,
            title: '',
            free_content: '',
            charge_content: '',
            price: '',
            is_free: 1,
            no_win_back: 2,
            exec_hh: 2,
            status: 1,
            sort: '',
            matches: ''
          })
          this.fanxians = []
          this.fanxian = []
          this.dataArrS = []
          console.log('这是反显', this.fanxians)
          this.getList()
        })
      }

      console.log(this.ruleForm)
    },
    // 执行发布操作
    executePublish() {
      const that = this

      // 转换数据格式 - 使用修改后的预测分类和赔率数据
      const finalMatchData = this.convertMatchDataForSubmit(this.ruleForm.matchList || [])

      console.log('提交的赛事数据:', finalMatchData)

      additionData({
        category: this.ruleForm.category,
        expert_id: this.ruleForm.expert_id,
        show_lx: this.ruleForm.show_lx,
        pass_lx: this.ruleForm.pass_lx,
        title: this.ruleForm.title,
        free_content: this.ruleForm.free_content,
        charge_content: this.ruleForm.charge_content,
        price: this.ruleForm.price,
        is_free: this.ruleForm.is_free,
        no_win_back: this.ruleForm.no_win_back,
        exec_hh: this.ruleForm.exec_hh,
        status: this.ruleForm.status,
        sort: this.ruleForm.sort,
        matches: JSON.stringify(finalMatchData),
        sf_pt: 2
      }).then(res => {
        if (res.code !== 1) {
          that.$message({
            type: 'error',
            message: res.msg
          })
          return false
        }
        // 不关闭弹窗，只显示发布成功提示
        aiRecommendreview({
          id: this.ruleForm.id
        })

        that.$message({
          type: 'success',
          message: '发布成功'
        })
        console.log(res)
      }).catch(error => {
        console.error('发布失败:', error)
        that.$message({
          type: 'error',
          message: '发布失败，请重试'
        })
      })
    },
    clickClose() {
      this.open = false
    },
    closeFormOpen() {
      this.open = false
    },
    clickType() {
      this.innerVisible = true
    },
    getInput() { },
    changeYuce() { },
    changeMatch() { },
    ConfirmOods() {
      this.innerVisible = false
    },
    changeOdds() { },
    changeOdds6() { },
    changeOdds7() { },
    changeOdds0() { },
    changeOdds1() { },
    changeOdds4() { },
    changeOdds5() { },
    toChange() { },
    timestampToTime(timestamp) {
      const date = new Date(timestamp * 1000)
      const M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
      const D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' '
      const h = date.getHours() + ':'
      const m = date.getMinutes()
      return M + D + h + m
    },
    // 解析付费内容，提取 data 字段
    parseChargeContent(chargeContent) {
      if (!chargeContent) return ''

      console.log('原始付费内容:', chargeContent)
      console.log('付费内容长度:', chargeContent.length)

      let result = ''

      // 先尝试直接解析 JSON
      try {
        const contentData = JSON.parse(chargeContent)
        console.log('JSON解析成功:', contentData)
        if (contentData.data) {
          result = contentData.data
          console.log('提取的data字段:', result)
        }
      } catch (e) {
        console.log('JSON解析失败:', e)
        // JSON 解析失败，尝试其他方法
      }

      // 如果不是标准 JSON，尝试正则提取 data 字段
      if (!result) {
        console.log('尝试正则提取data字段')
        // 使用更宽松的正则表达式来匹配 data 字段
        const dataMatch = chargeContent.match(/"data"\s*:\s*"((?:[^"\\]|\\.)*)"/)
        if (dataMatch && dataMatch[1]) {
          console.log('正则匹配成功:', dataMatch[1])
          // 处理转义字符
          result = dataMatch[1]
            .replace(/\\n/g, '\n')
            .replace(/\\r/g, '\r')
            .replace(/\\t/g, '\t')
            .replace(/\\"/g, '"')
            .replace(/\\\\/g, '\\')
          console.log('处理转义字符后:', result)
        }
      }

      // 如果都没有找到，直接返回原内容
      if (!result) {
        console.log('使用原始内容')
        result = chargeContent
      }

      console.log('最终解析结果长度:', result.length)
      console.log('最终解析结果:', result)

      // 根据比赛类型替换"数字+球"为"数字+分"
      return this.replaceBallToScore(result)
    },
    // 获取选中的赔率数据
    getSelectedOdds(match) {
      if (match.new_odds && match.new_odds.odds && Array.isArray(match.new_odds.odds)) {
        return match.new_odds.odds.filter(odd => odd.is_recommend === true)
      }
      return []
    },
    // 获取赛事的所有赔率数据 - 适配新的数据结构
    getAllOddsForMatch(match) {
      // 优先使用 new_odds 字段（用于修改时的渲染）
      if (match.new_odds && Array.isArray(match.new_odds) && match.new_odds.length > 0) {
        return match.new_odds[0] || []
      }
      // 如果没有 new_odds，使用 odds 字段
      if (match.odds && Array.isArray(match.odds) && match.odds.length > 0) {
        return match.odds[0] || []
      }
      return []
    },
    // 检查某个赔率是否已被选中 - 适配新的数据结构
    isOddSelected(match, odd) {
      // 优先使用 new_odds 字段（用于修改时的渲染）
      let oddsArray = []
      if (match.new_odds && Array.isArray(match.new_odds) && match.new_odds.length > 0) {
        oddsArray = match.new_odds[0] || []
      } else if (match.odds && Array.isArray(match.odds) && match.odds.length > 0) {
        oddsArray = match.odds[0] || []
      }

      return oddsArray.some(selectedOdd =>
        selectedOdd.label === odd.label && selectedOdd.value === odd.value
      )
    },
    // 处理赔率选择变化
    changeOddsForMatch(matchIndex, selectedOdds) {
      if (!this.ruleForm.matchList[matchIndex]) return

      // 更新对应赛事的选中赔率
      this.ruleForm.matchList[matchIndex].odds = {
        matchId: this.ruleForm.matchList[matchIndex].match_id,
        odds: selectedOdds
      }

      // 更新选中状态
      this.selectedOdds[matchIndex] = selectedOdds
    },

    // 生成方案标题

    // 重新生成付费内容
    regenerateChargeContent() {
      // 显示开始生成的提示
      this.$message({
        message: 'AI正在分析赛事数据，重新生成付费内容中...',
        type: 'info',
        duration: 3000
      })

      this.regenerateLoading = true
      console.log(this.ruleForm)

      const canshu = {
        expert_id: this.ruleForm.expert_id,
        category: 1,
        field: this.ruleForm.field,
        matchId: this.ruleForm.matchList.map(item => item.match_id),
        all_odds: this.ruleForm.matchList.map(item => item.all_odds),
        selected_odds: this.ruleForm.matchList.map(item => item.selected_odds)
      }

      // 显示进度提示
      const progressMessage = this.$message({
        message: '正在调用AI接口分析数据，请耐心等待...',
        type: 'warning',
        duration: 0, // 不自动关闭
        showClose: false
      })

      axios({
        method: 'post',
        url: 'https://expert.zctj16888.com/api/coze/analyze',
        data: canshu,
        timeout: 300000 // 设置300秒超时
      }).then(res => {
        // 关闭进度提示
        progressMessage.close()

        if (this.dialogTableVisible) {
          // 新增弹窗
          this.contentData2 = this.parseChargeContent(res.data.data.data)
        } else if (this.dialogTableModify) {
          // 修改弹窗
          this.contentData4 = this.parseChargeContent(res.data.data.data)
        }

        this.ruleForm.charge_content = this.parseChargeContent(res.data.data.data)

        this.regenerateLoading = false

        // 显示成功提示
        this.$message({
          message: '✅ 付费内容重新生成成功！AI已为您生成了新的分析内容',
          type: 'success',
          duration: 4000
        })
      }).catch(error => {
        // 关闭进度提示
        progressMessage.close()
        this.regenerateLoading = false

        console.error('重新生成付费内容失败:', error)

        // 显示错误提示
        this.$message({
          message: '❌ 重新生成失败，请检查网络连接或稍后重试',
          type: 'error',
          duration: 5000
        })
      })
    },
    // 生成新的付费内容（示例函数）
    generateNewChargeContent() {
      const matchInfo = this.ruleForm.matchList && this.ruleForm.matchList.length > 0
        ? this.ruleForm.matchList.map(match => {
          const teamNames = this.ruleForm.category === 2
            ? `${match.away_team_name} VS ${match.home_team_name}`
            : `${match.home_team_name} VS ${match.away_team_name}`
          return teamNames
        }).join(' | ')
        : '暂无赛事信息'

      return `
        <h3>AI智能分析推荐</h3>
        <p><strong>赛事分析：</strong>${matchInfo}</p>
        <p><strong>推荐理由：</strong></p>
        <ul>
          <li>基于历史数据深度分析</li>
          <li>结合实时赔率变化趋势</li>
          <li>专家团队专业研判</li>
          <li>多维度风险评估</li>
        </ul>
        <p><strong>投注建议：</strong>建议合理分配资金，控制风险，理性投注。</p>
        <p><em>本推荐仅供参考，请根据自身情况谨慎决策。</em></p>
      `
    },
    // 获取赔率数据
    async getMatchesOdds(lx, matchIds) {
      try {
        const response = await axios.post('https://api.zctj16888.com/api/v1/AiPresets/getMatchesOdds', {
          lx: lx, // 足球1 篮球2
          match_ids: matchIds // 赛事ID数组
        })

        console.log('获取赔率数据成功:', response.data)
        return response.data
      } catch (error) {
        console.error('获取赔率数据失败:', error)
        throw error
      }
    },
    // 计算双方交战数据
    calculateMatchStats(historyList, homeTeam, awayTeam) {
      if (!historyList || historyList.length === 0) return null

      let homeGoals = 0
      let awayGoals = 0
      let matchCount = 0

      historyList.forEach(match => {
        // 检查这场比赛是否包含当前的两个队伍
        const hasHomeTeam = match.team_A_name === homeTeam || match.team_B_name === homeTeam
        const hasAwayTeam = match.team_A_name === awayTeam || match.team_B_name === awayTeam

        if (hasHomeTeam && hasAwayTeam) {
          matchCount++
          // 计算主队进球数
          if (match.team_A_name === homeTeam) {
            homeGoals += parseInt(match.fs_A) || 0
            awayGoals += parseInt(match.fs_B) || 0
          } else {
            homeGoals += parseInt(match.fs_B) || 0
            awayGoals += parseInt(match.fs_A) || 0
          }
        }
      })

      if (matchCount === 0) return null

      const avgHomeGoals = (homeGoals / matchCount).toFixed(1)
      const avgAwayGoals = (awayGoals / matchCount).toFixed(1)

      return `双方近${matchCount}次交战，${homeTeam}进${homeGoals}球，失${awayGoals}球，场均进失球 ${avgHomeGoals}-${avgAwayGoals}`
    }
  }
}
</script>

<style src="@wangeditor/editor/dist/css/style.css"></style>
<style>
.addBtn {
  margin: 30px 0 30px 30px;
}

.inout {
  display: flex;
  align-items: center;
}

.ql-clipboard {
  position: fixed;
  display: none;
  left: 50%;
  top: 50%;
}

.link-type {
  color: #409EFF;
  cursor: pointer;
}

.link-type:hover {
  color: #66b1ff;
}

/* 赔率选择样式 */
.odds-checkbox {
  width: 100%;
  height: auto;
  border-radius: 6px;
  transition: all 0.3s ease;
}

.odds-checkbox:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.el-checkbox-button.is-checked {
  background-color: #67c23a !important;
  border-color: #67c23a !important;
  color: #fff !important;
  box-shadow: 0 2px 8px rgba(103, 194, 58, 0.3);
}

.el-checkbox-button.is-checked .el-checkbox-button__inner {
  background-color: #67c23a !important;
  border-color: #67c23a !important;
  color: #fff !important;
}

.el-checkbox-button__inner {
  border-radius: 6px;
  border: 1px solid #dcdfe6;
  background-color: #fff;
  color: #606266;
  padding: 0;
  width: 100%;
  height: auto;
  min-height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.el-checkbox-button:first-child .el-checkbox-button__inner {
  border-left: 1px solid #dcdfe6;
  border-radius: 6px;
}

.el-checkbox-button:last-child .el-checkbox-button__inner {
  border-radius: 6px;
}

.match-odds-container {
  margin-bottom: 20px;
  padding: 15px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background-color: #fafafa;
}

.match-title {
  margin-bottom: 10px;
  font-weight: bold;
  color: #303133;
}

.odds-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.odds-button {
  min-width: 60px;
  text-align: center;
}
</style>
